<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts';
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/util/util'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    chartType: {
      type: String,
      default: 'ychart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '0px'
    },
    taskData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      chart: null,
      taskName: [],
      taskVal: []
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      const that = this
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        grid: {
          top:48
        },
        legend: {
          orient: 'vertical',
          right: 10,
          formatter(name) {
            if (that.taskData.length > 0) {
              const value = that.taskData.find(v => v.name === name).value
              return [`{name|${name}}`, `{value|${value}}个`].join('   ')
            }
          },
          textStyle: {
            color: 'rgba(177, 245, 254, 1)',
            fontWeight: 'bold',
            rich: {
              name: {fontSize: 14},
              value: {fontSize: 12}
            }
          },
        },
        series: [
          {
            name: 'Nightingale Chart',
            type: 'pie',
            radius: ['40%', '70%'],
            data: this.taskData,
            label: {
              formatter: `{b}   {percent|{d} %}`,
              textStyle: {
                color: 'rgba(177, 245, 254, 1)'
              },
              rich: {
                percent: {
                  fontSize: 10,
                  color: '#FFFFFF'
                }
              }
            }
          }
        ]
      })
    }
  }
}
</script>
